package com.base.demo.design.play;

import java.util.*;

/**
 * @Description: 并发修改异常测试
 * @BelongsProject: base-demo-design
 * @BelongsPackage: com.base.demo.design.play
 * @Author: ChenYongJia
 * @CreateTime: 2021-08-19 15:41
 * @Email: chen87647213@163.com
 * @Version: 1.0
 */
public class ConcurrentModificationExceptionTest {

    public static void main(String[] args) {
        Map<String, String> hashtable = new Hashtable<>();
        hashtable.put("t1", "1");
        hashtable.put("t2", "2");
        hashtable.put("t3", "3");

        Enumeration<Map.Entry<String, String>> iterator1 = (Enumeration<Map.Entry<String, String>>) hashtable.entrySet().iterator();
        hashtable.remove(iterator1.nextElement().getKey());
        while (iterator1.hasMoreElements()) {
            System.out.println(iterator1.nextElement());
        }

        // 无法预估初始化容量时无脑填入16，这个值可以写在全局常量
        Map<String, String> hashMap = new HashMap<>(16);
        hashMap.put("h1", "1");
        hashMap.put("h2", "2");
        hashMap.put("h3", "3");

        Iterator<Map.Entry<String, String>> iterator2 = hashMap.entrySet().iterator();
        hashMap.remove(iterator2.next().getKey());
        while (iterator2.hasNext()) {
            System.out.println(iterator2.next());
        }

    }

}
